<template>
  <div class="">
    <el-upload
        class="upload_wrapper"
        :class="fileList.length >= limit ? 'hide' : ''"
        :file-list="fileList"
        ref="fileUpload"
        :action="uploadFileUrl"
        :headers="uploadHeaders"
        :multiple="multiple"
        :show-file-list="true"
        list-type="text"
        :on-remove="handleDelete"
        :limit="limit"
        :on-success="handleSuccess"
        :on-exceed="handleExceed"
        :on-error="handleUploadError"
        :before-upload="handleBeforeUpload"
        :before-remove="handleBeforeRemove"
    >
      <el-button type="primary">
        <el-icon><Plus /></el-icon>
        上传文件
      </el-button>
    </el-upload>

    <!-- <div class="el-upload__tip" v-if="isShowTip">
      请上传
      <template v-if="fileType">格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
      的文件
    </div> -->
  </div>
</template>

<script setup>
import feedback from '@/utils/feedback'
import { ref, watch, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import {useUserStore} from "../../stores/user.js";
import pinia from "../../stores/store.js";

const uploadFileUrl = `${import.meta.env.VITE_APP_BASE_API}/file/upload`
const baseUrl = import.meta.env.VITE_APP_BASE_API

const fileList = ref([])
const number = ref(0)
const uploadList = ref([])
const fileUpload = ref(null)
const previousFileList = ref([])

const emit = defineEmits(["update:modelValue"])

const props = defineProps({
  size: {
    type: String,
    default: 'default',
  },
  modelValue: {
    type: String,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  limit: {
    type: Number,
    default: 1,
  },
  fileSize: {
    type: Number,
    default: 10,
  },
  // 文件类型, 例如 ['pdf', 'doc', 'docx']
  fileType: {
    type: Array,
    default: () => ["pdf", "doc", "docx",'ppt','pptx'],
  },
  isShowTip: {
    type: Boolean,
    default: true
  }
})
const uploadHeaders=ref( ``)
const store = useUserStore(pinia)
if(store.token){
  uploadHeaders.value={
    Authorization: `Bearer ${store.token}`
  }
}
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    const list = Array.isArray(newVal) ? newVal : newVal.split(',')
    fileList.value = list.map(item => {
      if (typeof item === 'string') {
        return { name: item, url: item }
      }
      return item
    })
  } else {
    fileList.value = []
  }
}, { immediate: true, deep: true })

const handleSuccess = (res, file) => {
  if (res.code === 200) {
    uploadList.value.push({ name: res.data.alt || file.name, url: res.data.url })
    uploadedSuccessfully()
  } else {
    number.value--
    feedback.closeLoading()
    feedback.msgError(res.msg)
    fileUpload.value.handleRemove(file)
    uploadedSuccessfully()
  }
}

const uploadedSuccessfully = () => {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.concat(uploadList.value)
    uploadList.value = []
    number.value = 0
    emit("update:modelValue", listToString(fileList.value))
    feedback.closeLoading()
  }
}

const handleBeforeUpload = (file) => {
  let fileExtension = ""
  if (file.name.lastIndexOf(".") > -1) {
    fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1).toLowerCase()
  }

  // const isAllowed = props.fileType.some(type => {
  //   return fileExtension === type.toLowerCase()
  // })

  // if (!isAllowed) {
  //   feedback.msgError(`请上传${props.fileType.join('/')}格式的文件！`)
  //   return false
  // }

  // const isLt = file.size / 1024 / 1024 < props.fileSize
  // if (!isLt) {
  //   feedback.msgError(`上传文件大小不能超过 ${props.fileSize}MB!`)
  //   return false
  // }

  feedback.loading("正在上传文件，请稍候...")
  number.value++
}

const handleUploadError = () => {
  feedback.msgError("上传文件失败，请重试")
  feedback.closeLoading()
}

const handleExceed = () => {
  feedback.msgError(`上传文件数量不能超过 ${props.limit} 个!`)
}

const handleBeforeRemove = () => {
  previousFileList.value = [...fileList.value]
}

const handleDelete = (file) => {
  const findex = previousFileList.value.map(f => f.name).indexOf(file.name)
  if (findex > -1) {
    fileList.value.splice(findex, 1)
    emit("update:modelValue", listToString(fileList.value))
  }
}

const listToString = (list, separator = ',') => {
  let strs = list.map(item => item.url.replace(baseUrl, '')).join(separator)
  return strs
}
</script>

<style scoped lang="scss">
.upload_wrapper.hide :deep() .el-upload {
  display: none;
}
</style>
